import { useKeyPress } from 'ahooks'
import { useDispatch } from 'react-redux'
import { ActionCreators } from 'redux-undo'
import {
  removeSelectedComponent,
  copySelectedCompoent,
  pasteSelectedCompoent,
  selectedPrevCompoent,
  selectedNextCompoent,
} from '../store/componetnsReducer'
//判断光标是否在选择组件内部
function isActiveElementValid() {
  const activeElement = document.activeElement
  //没有增加dnd-kit之前
  // if (activeElement === document.body) return true //说明光标没有选择到input框
  //增加之后
  if (activeElement === document.body) return true
  if (activeElement?.matches('div[role="button"')) return true

  return false
}
function useBindCanvasKeyPress() {
  const dispatch = useDispatch()
  //删除组件
  useKeyPress(['backspace', 'delete'], () => {
    if (!isActiveElementValid()) return
    dispatch(removeSelectedComponent())
  })
  //复制
  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActiveElementValid()) return
    dispatch(copySelectedCompoent())
  })
  // 粘贴
  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActiveElementValid()) return
    dispatch(pasteSelectedCompoent())
  })
  //选中上一个
  useKeyPress('uparrow', () => {
    if (!isActiveElementValid()) return
    dispatch(selectedPrevCompoent())
  })
  //选择下一个
  useKeyPress('downarrow', () => {
    if (!isActiveElementValid()) return
    dispatch(selectedNextCompoent())
  })
  //撤销
  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(ActionCreators.undo())
    },
    {
      exactMatch: true, //严格匹配
    }
  )
  //取消撤销
  useKeyPress(
    ['ctrl.shift.z', 'meta.shift.z'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(ActionCreators.redo())
    },
    { exactMatch: true }
  )
}
export default useBindCanvasKeyPress
